package com.vinny.springbootflowable.controller;

import com.vinny.springbootflowable.common.ApiResponse;
import com.vinny.springbootflowable.common.HttpStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 认证控制器
 * 同时支持页面渲染和RESTful API
 */
@Tag(name = "认证管理", description = "用户登录登出相关接口")
@Controller
@RequestMapping("/api/auth")
public class AuthController {

    // ================ 视图相关接口 ================

    /**
     * 登录页面
     */
    @GetMapping("/login")
    public String login(
            @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout,
            Model model) {
        
        if (error != null) {
            model.addAttribute("error", "用户名或密码错误");
        }

        if (logout != null) {
            model.addAttribute("msg", "您已成功退出系统");
        }

        // 如果用户已登录，直接跳转到首页
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getPrincipal())) {
            return "redirect:/";
        }

        return "login";
    }

    /**
     * 首页
     */
    @GetMapping("/")
    public String index(Authentication authentication, Model model) {
        if (authentication != null && authentication.isAuthenticated()) {
            model.addAttribute("username", authentication.getName());
            model.addAttribute("roles", authentication.getAuthorities());
            return "index";
        }
        return "redirect:/login";
    }

    /**
     * 退出登录（页面）
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return "redirect:/login?logout";
    }

    // ================ RESTful API 接口 ================

    /**
     * 获取当前用户信息
     */
    @GetMapping("/user")
    @ResponseBody
    public ApiResponse<Map<String, Object>> getCurrentUser(Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated() || 
            "anonymousUser".equals(authentication.getPrincipal())) {
            return ApiResponse.error(HttpStatus.UNAUTHORIZED, "未登录");
        }

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", authentication.getName());
        userInfo.put("roles", authentication.getAuthorities().stream()
                .map(auth -> auth.getAuthority())
                .collect(Collectors.toList()));

        return ApiResponse.success(userInfo);
    }

    /**
     * 登录状态检查
     */
    @GetMapping("/check")
    @ResponseBody
    public ApiResponse<Void> checkLoginStatus(Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated() || 
            "anonymousUser".equals(authentication.getPrincipal())) {
            return ApiResponse.error(HttpStatus.UNAUTHORIZED, "未登录");
        }
        return ApiResponse.success();
    }

    /**
     * 退出登录（API）
     */
    @PostMapping("/logout")
    @ResponseBody
    public ApiResponse<Void> apiLogout(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
            return ApiResponse.success();
        }
        return ApiResponse.error(HttpStatus.BAD_REQUEST, "未登录状态");
    }

    /**
     * 登录接口
     */
    @Operation(summary = "用户登录")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "登录成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "用户名或密码错误")
    })
    @PostMapping("/login")
    @ResponseBody
    public ApiResponse<Map<String, Object>> login(@Parameter(description = "用户名") @RequestParam String username, @Parameter(description = "密码") @RequestParam String password) {
        // 实际的登录处理由 Spring Security 的过滤器链完成
        // 如果到达这里，说明登录失败
        return ApiResponse.error(HttpStatus.UNAUTHORIZED, "用户名或密码错误");
    }
} 